// src/stores/planV2.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import dayjs from 'dayjs';
import quarterOfYear from 'dayjs/plugin/quarterOfYear';
import { getPlanV2Api, addPlanV2Api, updatePlanV2Api } from '@/api/plan';
import { deletePlanV2Api } from '../api/plan';

// 注册dayjs插件
dayjs.extend(quarterOfYear);

// 计划类型常量
export const PLAN_TYPES = {
    WATER: 1,
    ELECTRICITY: 2,
    GAS: 3
};

export const usePlanV2Store = defineStore('planV2', () => {
    // 状态
    const allPlansData = ref([]);
    const loading = ref(false);
    const currentYear = ref(dayjs().format('YYYY'));
    const activeTab = ref('water'); // 默认显示水

    // 计算属性
    const currentPlanTypeId = computed(() => {
        switch (activeTab.value) {
            case 'water': return PLAN_TYPES.WATER;
            case 'electricity': return PLAN_TYPES.ELECTRICITY;
            case 'gas': return PLAN_TYPES.GAS;
            default: return PLAN_TYPES.WATER;
        }
    });

    const currentYearNum = computed(() => {
        return Number(currentYear.value);
    });

    // 格式化时间字符串 - 仅用于内部处理
    const formatTimeString = (timestamp, type) => {
        const date = dayjs(timestamp);

        if (type === 'month') {
            return date.format('YYYY-MM-01');
        } else if (type === 'quarter') {
            return `${date.format('YYYY第Q')}季度`;
        } else if (type === 'year') {
            return date.format('YYYY');
        }
        return '';
    };

    // 处理计划数据 - 仅用于内部处理
    const processPlans = (plans, planType, selectedYear) => {
        const monthPlans = [];
        const quarterPlans = [];
        const yearPlans = [];

        plans.forEach(plan => {
            // 过滤出当前选中类型的计划
            if (plan.type !== planType) return;

            // 过滤出当前选中年份的计划
            const planYear = dayjs(plan.start_time).year();
            if (selectedYear && planYear !== selectedYear) return;

            // 使用dayjs计算日期差
            const startDate = dayjs(plan.start_time);
            const endDate = dayjs(plan.end_time);
            const diffDays = endDate.diff(startDate, 'day');

            // 转换数据格式，添加到对应数组
            const formattedPlan = {
                id: plan.id,
                start_time: '',
                usage: Number(plan.value)
            };

            if (diffDays <= 31) {
                formattedPlan.start_time = formatTimeString(plan.start_time, 'month');
                monthPlans.push(formattedPlan);
            } else if (diffDays <= 100) {
                formattedPlan.start_time = formatTimeString(plan.start_time, 'quarter');
                quarterPlans.push(formattedPlan);
            } else {
                formattedPlan.start_time = formatTimeString(plan.start_time, 'year');
                yearPlans.push(formattedPlan);
            }
        });

        return { monthPlans, quarterPlans, yearPlans };
    };

    // 计算过滤后的数据
    const filteredMonthlyData = computed(() => {
        const { monthPlans } = processPlans(
            allPlansData.value,
            currentPlanTypeId.value,
            currentYearNum.value
        );
        return monthPlans;
    });

    const filteredQuarterlyData = computed(() => {
        const { quarterPlans } = processPlans(
            allPlansData.value,
            currentPlanTypeId.value,
            currentYearNum.value
        );
        return quarterPlans;
    });

    const filteredYearlyData = computed(() => {
        const { yearPlans } = processPlans(
            allPlansData.value,
            currentPlanTypeId.value,
            currentYearNum.value
        );
        return yearPlans;
    });

    /**
     * 获取计划数据
     * @param {number} companyId - 公司ID
     * @returns {Promise} 返回获取数据的Promise
     */
    const fetchPlanData = async (companyId) => {
        if (!companyId) return Promise.reject(new Error('未提供公司ID'));

        try {
            loading.value = true;

            const params = {
                company_id: companyId
            };

            const { data } = await getPlanV2Api(params);

            if (data && data.length > 0) {
                // 保存所有获取的计划数据
                allPlansData.value = data;
            } else {
                // 清空数据
                allPlansData.value = [];
            }

            return data;
        } catch (error) {
            console.error('获取计划数据失败:', error);
            // 清空数据
            allPlansData.value = [];
            return Promise.reject(error);
        } finally {
            loading.value = false;
        }
    };

    /**
     * 添加计划
     * @param {Object} requestData - 请求数据
     * @returns {Promise} 返回添加计划的Promise
     */
    const addPlanV2 = async (requestData) => {
        try {
            loading.value = true;
            const result = await addPlanV2Api(requestData);
            return result;
        } catch (error) {
            console.error('添加计划失败:', error);
            return Promise.reject(error);
        } finally {
            loading.value = false;
        }
    };

    /**
     * 更新计划
     * @param {Object} requestData - 请求数据
     * @returns {Promise} 返回更新计划的Promise
     */
    const updatePlanV2 = async (requestData) => {
        try {
            loading.value = true;
            const result = await updatePlanV2Api(requestData);
            return result;
        } catch (error) {
            console.error('更新计划失败:', error);
            return Promise.reject(error);
        } finally {
            loading.value = false;
        }
    };
    /**
    * 删除计划
    * @param {Object} requestData - 请求数据
    * @param {number} requestData.id - 计划ID
    * @returns {Promise} 返回更新计划的Promise
    */
    const deletePlanV2 = async (requestData) => {
        console.log('requestData: ', requestData);
        try {
            loading.value = true;

            const result = await deletePlanV2Api(requestData);
            return result;
        } catch (error) {
            console.error('删除计划失败:', error);
            return Promise.reject(error);
        } finally {
            loading.value = false;
        }
    };

    // 设置当前年份
    const setCurrentYear = (year) => {
        currentYear.value = year;
    };

    // 设置活动标签
    const setActiveTab = (tab) => {
        activeTab.value = tab;
    };

    return {
        // 状态
        allPlansData,
        loading,
        currentYear,
        activeTab,

        // 计算属性
        currentPlanTypeId,
        currentYearNum,
        filteredMonthlyData,
        filteredQuarterlyData,
        filteredYearlyData,

        // 方法
        fetchPlanData,
        addPlanV2,
        updatePlanV2,
        deletePlanV2,
        setCurrentYear,
        setActiveTab,

        // 常量
        PLAN_TYPES
    };
});